package com.kehutong.contact.admin;

import com.kehutong.common.ExcelUtil;
import com.kehutong.common.entity.Root;
import com.kehutong.common.util.Token;
import com.kehutong.contact.entity.Contact;
import com.kehutong.contact.entity.Customer;
import com.kehutong.contact.service.CustomerService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;

import java.io.File;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author liujinwang
 * @description 客户管理
 */
@MvcAction
@ReqMapping("/admin/crm/customer")
public class CustomerController {

    static final Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private CustomerService customerService;

    @ReqMapping("/page")
    public Page<Customer> page(JSONObject jsonObject) throws Exception {
        return customerService.page(jsonObject);
    }

    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) throws Exception{
        return customerService.list(jsonObject);
    }

    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    public Object save(Token token, Customer customer, Contact contact) throws Exception{
        return customerService.save(token,customer,contact);
    }

    @Bean(copy = true)
    @ReqMapping("/update")
    public Object update(Customer customer,Token token) throws Exception {
        return customerService.update(customer,token);
    }

    @ReqMapping("/delete")
    public Object delete(Customer customer) throws Exception{
        return customerService.delete(customer);
    }

    @ReqMapping("/get")
    public Object get(Customer customer) throws Exception{
        customer = Pool.get(Customer.class, customer.getId());
        return Result.success(customer);
    }

    @Bean(copy = true)
    @ReqMapping("/updateFocus")
    public Object updateFocus(Customer customer,Token token) throws Exception {
        customer.setFocus(!customer.isFocus());
        return customerService.update(customer, token);
    }

    /**
     * 根据条件导出客户数据
     *
     * @param jsonObject 条件对象
     * @return 文件
     * @throws Exception 异常
     */
    @ReqMapping("/export")
    public Object exportData(JSONObject jsonObject, Token token) throws Exception {
        if (!Root.isRoot(token.getUuid())) {
            jsonObject.put("exportUsername",token.getUsername());
        }
        jsonObject.put("pageNo", 1);
        jsonObject.put("pageSize", Short.MAX_VALUE);
        Page<Customer> page =customerService.page(jsonObject);
        File dataFile = exportDataFile(page.getList());
        return com.kehutong.common.errcode.Result.download(dataFile);
    }

    private File exportDataFile(List<Customer> list) throws Exception{
        Workbook wb = exportWorkBook(list);
        return ExcelUtil.writeXlsFile(wb, "客户列表_" + System.currentTimeMillis(), ".xls");
    }
    private Workbook exportWorkBook(List<Customer> list) {

        // 生成模板文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工具
        CreationHelper helper = wb.getCreationHelper();
        //单元格样式类
        CellStyle dateCellStyle = wb.createCellStyle();
        //设置单元格格式
        //dateCellStyle.setDataFormat(helper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));

        Sheet sheet = wb.createSheet();
        Row headerRow = sheet.createRow(0);
        int headerCellNum = 0;
        String[] chargeUserInstrument = {"客户名称", "客户类型", "客户状态","客户星级","首联系人","手机号码","客户来源","最后跟进","未跟进天数"};
        for (String s : chargeUserInstrument) {
            Cell cell = headerRow.createCell(headerCellNum++);
            cell.setCellValue(s);
        }
        int cellNum = 0;
        for (int i = 0; i < list.size(); i++) {
            Customer customer = list.get(i);
            Row row = sheet.createRow(i + 1);
            cellNum = 0;
            row.createCell(cellNum++).setCellValue(customer.getCorpFullName());
            row.createCell(cellNum++).setCellValue(customer.getCustomerType().getDesc());
            row.createCell(cellNum++).setCellValue(customer.getCustomerStatus().getDesc());
            row.createCell(cellNum++).setCellValue(customer.getCustomerStar());
            row.createCell(cellNum++).setCellValue(customer.getContactName());
            row.createCell(cellNum++).setCellValue(customer.getMobile());
            row.createCell(cellNum++).setCellValue(customer.getCustomerSource().getDesc());
            row.createCell(cellNum++).setCellValue(customer.getLastFollowUpTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            row.createCell(cellNum++).setCellValue(customer.getNoContactDays());

           /* Cell tmpCell = row.createCell(cellNum++);
            tmpCell.setCellStyle(dateCellStyle);
            tmpCell.setCellValue(customer.getCreateTime());*/
        }
        // 自动列宽
        for (int i = 0; i < cellNum; i++) {
            if (i == 0) {
                // id列不调整
                continue;
            }
            // 自动列宽
            ExcelUtil.autoSizeColumn(sheet, i);
        }
        return wb;
    }
}
